package org.tungse.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
import org.tungse.domain.User;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : Tungse
 * @Date: 2025/7/2 10:34
 * @Description:
 */
@Service
public class UserService{
    //模拟查询数据库数据，返回结果
    public List<User> getList() {
        List<User> userList = new ArrayList<>();
        userList.add(new User("1", "周慧敏", 18));
        userList.add(new User("2", "关之琳", 20));
        userList.add(new User("3", "王祖贤", 21));
        return userList;
    }



    //资源名称
    public static final String RESOURCE_NAME_QUERY_USER_BY_NAME = "queryUserByUserName";

    /**
     * 注解的方式限流
     */
    //value是资源名称，是必填项。blockHandler填限流处理的方法名称
    @SentinelResource(value = RESOURCE_NAME_QUERY_USER_BY_NAME, blockHandler = "queryUserByUserNameBlock",
        fallback = "queryUserByUserNameFallBack") //blockHandlerClass是限流处理的方法所在的类
    public User queryByUserName(String userName) {
//        if (userName == null || "".equals(userName)) {
//            //抛出异常
//            throw new RuntimeException("queryByUserName() command failed, userName is null");
//        }
        //模拟随机异常
        int i = Integer.parseInt(userName);
        System.out.println(i);
        return new User("0", userName, 18);
    }


    //注意细节，一定要跟原函数的返回值和形参一致，并且形参最后要加个BlockException参数
    //否则会报错，FlowException: null
    public User queryUserByUserNameBlock(String userName, BlockException ex) {
        //打印异常
        ex.printStackTrace();
        return new User("xxx", "用户名称：{" + userName + "},资源访问被限流", 0);
    }

    public User queryUserByUserNameFallBack(String userName, Throwable ex) {
        //打印日志
        ex.printStackTrace();
        return new User("-1", "用户名称：{" + userName + "},系统异常，请稍后重试", 0);
    }
}